package org.example;

public class Main {
    private static BettingServer server;

    public static void main(String[] args) {
        // 添加关闭钩子（尽早注册）
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\nReceived shutdown signal...");
            shutdown();
        }));

        try {
            // 创建并启动服务器
            server = new BettingServer();
            server.start();
            System.out.println("Betting org.example.server started on port 8001");

            // 显示初始状态
//            org.example.server.checkStatus();

            // 保持服务器运行
            System.out.println("\nServer is running.");
            System.out.println("  GET  http://localhost:8001/{customerId}/session");
            System.out.println("  POST http://localhost:8001//{betOfferId}/stake?sessionkey={sessionKey}");
            System.out.println("  GET  http://localhost:8001//{betOfferId}/highstakes");
            Thread.currentThread().join();

        } catch (Exception e) {
            System.err.println("Failed to start org.example.server: " + e.getMessage());
            e.printStackTrace();
            shutdown();
        }
    }

    /**
     * 优雅关闭
     */
    private static void shutdown() {
        System.out.println("\n=== Starting Shutdown Sequence ===");

        long startTime = System.currentTimeMillis();

        if (server != null) {
            try {
                server.stop();
            } catch (Exception e) {
                System.err.println("Error during graceful shutdown: " + e.getMessage());
                System.out.println("Attempting forced shutdown...");
            }
        }

        long duration = System.currentTimeMillis() - startTime;
        System.out.println("=== Shutdown Completed in " + duration + "ms ===");
    }

}